package com.filter;

import com.bean.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class FilterTest implements Filter {
    public void destroy() {
    }

    //进入过滤器
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("进入过滤器");
        //获取当前网址名字
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response=(HttpServletResponse)resp;
        String path = request.getServletPath();
        System.out.println(path);
        if (path.equals("/login.jsp") || path.equals("/index.jsp") || path.startsWith("/js") ||
                path.startsWith("/css") || path.startsWith("/img") ||
                path.equals(((HttpServletRequest) req).getContextPath() + "/authCode")) {
            //允许该请求通过页面,主页和登录页面
            chain.doFilter(req, resp);
        } else {//判断用户是否登录
            System.out.println("没有登录");
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute("user");
            if (user == null) {//没有登录,不允许进入后台页面和购物车页面
                //返回登录页面
                response.sendRedirect(((HttpServletRequest) req).getContextPath()+"/login.jsp");
            }else{
                //进入相关页面
                chain.doFilter(req, resp);
            }
        }
        System.out.println("退出过滤器");
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
